import Common
from M3u8List import M3u8

class PlaylistHelper(object):
    TS_TYPE = 0
    M3U8_TYPE = 1
    
    def __init__(self, logFile):
        self.m3u8 = M3u8()
        self.logger = logFile
    
    def Begin(self, mov_ts):
        sequence = Common.SequenceNumber(mov_ts)
        maxDuration = 8
        self.logger.logthis("Setting Header: MaxDuration: " + str(maxDuration) + " and base sequence#: " + str(sequence), Common.Logger.GET_Request)
        self.m3u8.InitHeader(maxDuration, sequence)
    
    def Push_Back(self, element, type):
        if type == PlaylistHelper.TS_TYPE:
            self.m3u8.InsertTS(element, "#EXTINF:5,")
        elif type == PlaylistHelper.M3U8_TYPE:
            self.InsertPlaylist(element)
    
    def InsertPlaylist(self, plM3u8):
        if plM3u8.header[M3u8.TargetDuration] > self.m3u8.header[M3u8.TargetDuration]:
            maxDuration = plM3u8.header[M3u8.TargetDuration]
            self.m3u8.header[M3u8.TargetDuration] = maxDuration
            self.logger.logthis("Trying to insert ad:: Setting Header: MaxDuration: " + str(maxDuration), Common.Logger.GET_Request)
        
        self.logger.logthis("Ad insert begin", Common.Logger.GET_Request)
        self.Begin_Discontinuity()
        self.m3u8.ExtendTS(plM3u8.TS_list)
        self.END_Discontinuity()
        self.logger.logthis("Ad insert End", Common.Logger.GET_Request)
    
    def Begin_Discontinuity(self):
        self.m3u8.InsertDiscontuinity()
    
    def END_Discontinuity(self):
        self.m3u8.InsertDiscontuinity()
    
    def End(self):
        pass
       
    def WriteToStdOut(self):
        self.logger.logthis("Writing playlist to output", Common.Logger.GET_Request)
        #write both header and content output
        tempFile = self.Dump("temp.m3u8")
        
        Common.writeHeaderToOutput(tempFile.name)
        Common.writeFileToStdout(tempFile.name)
        Common.DeleteFile(tempFile.name)
        
    def Dump(self, fileName):
        tempFile = open(fileName, 'w')
        self.m3u8.Write(tempFile)
        tempFile.close()
        return tempFile